﻿// <copyright file="Material3Controller.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace MesAPI.Controllers.Material
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using Newtonsoft.Json;
    using PublicData;
    using PublicFunction;
    using XinjeMesProgram.Entities;
    using XinjeMesProgram.Entities.Maintenance;
    using XinjeMesProgram.Entities.Material;
    using XinjeMesProgram.Models;

    /// <summary>
    /// 物料追踪子表控制器.
    /// </summary>
    [ApiController] // [ApiController] 必须加不然你调用不了参数
    [Authorize]
    public class Material3Controller : ControllerBase
    {
#pragma warning disable SA1000 // Keywords should be spaced correctly
#pragma warning disable CS8600 // 将 null 字面量或可能为 null 的值转换为非 null 类型。
#pragma warning disable CS8602 // 解引用可能出现空引用。
#pragma warning disable CS8604 // 引用类型参数可能为 null。
        private readonly ResponseModel response = new();

        /// <summary>
        /// 子表查询.
        /// </summary>
        /// <param name="pageSize">每页记录数.</param>
        /// <param name="currentPage">当前页码.</param>
        /// <param name="id">主表与子表的关联id.</param>
        /// <param name="workOrderNumber">工单号.</param>
        /// <param name="serialNumber">序列号.</param>
        /// <param name="condition">在库状态.</param>
        /// <param name="state">状态.</param>
        /// <param name="oN2">打印开关.</param>
        /// <returns>返回物料记录子表数据.</returns>
        [Route("/api/v1/material/materialRecord2")]
        [HttpGet]
        public ResponseModel MaterialRecord2(int pageSize, int currentPage, string id, string? workOrderNumber, string? serialNumber, int? condition, int? state, int oN2)
        {
            using (FactoryMesContext context = new())
            {
                var query1 = from m in context.MaterialTracking3 // content后跟数据库实体名称
                             where m.Id2 == id
                             orderby m.EndDate descending
                             select new MaterialData2model
                             {
                                 Id = m.Id, // 唯一Id
                                 Id2 = m.Id2, // 主表子表关联Id
                                 WorkOrderNumber = m.WorkOrderNumber, // 工单号
                                 SerialNumber = m.SerialNumber, // 序列号
                                 Condition = m.Condition, // 在库状态
                                 DeliveryDate = m.DeliveryDate, // 发货日期（现改为入库日期）
                                 OutboundDate = m.OutboundDate, // 出库日期
                                 EndDate = m.EndDate, // 跟踪结束日期
                                 ScreenPrinting = m.ScreenPrinting, // PCB丝印
                                 State = m.State, // 0:正常 1：待核对 2：异常
                                 IsJudge = m.IsJudge, // 是否判断过（0：无 1：判断过）
                             };

                // 在库状态
                if (condition == 100)
                {
                    query1 = query1.Where(x => x.Condition == 0 || x.Condition == 1);
                }
                else
                {
                    query1 = query1.Where(x => x.Condition == condition);
                }

                // 产片状态
                if (state == 100)
                {
                    query1 = query1.Where(x => x.State == 0 || x.State == 1 || x.State == 2);
                }
                else
                {
                    query1 = query1.Where(x => x.State == state);
                }

                // 序列号
                if (!string.IsNullOrEmpty(serialNumber))
                {
                    query1 = query1.Where(x => x.SerialNumber.Contains(serialNumber));
                }

                // 工单号
                if (!string.IsNullOrEmpty(workOrderNumber))
                {
                    query1 = query1.Where(x => x.WorkOrderNumber.Contains(workOrderNumber));
                }

                List<MaterialData2model> list1 = query1.ToList();

                // 正常查询
                if (oN2 == 0)
                {
                    this.response.SetData(list1.ListPaged(currentPage, pageSize), list1.Count);
                }

                // 子表导出数据
                else if (oN2 == 1)
                {
                    string dateTimeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); // 时间戳

                    // string randomString = Path.GetRandomFileName().Replace(".", string.Empty); // 随机字符串
                    string fileName = $"file_{dateTimeStamp}.csv"; // 定义文件名
                    string filePath = Path.Combine("C:\\WebSite\\XinjeMesApi\\wwwroot\\son", fileName);

                    string conditionText = string.Empty;
                    string stateText = string.Empty;
                    string isJudgeText = string.Empty;

                    using (StreamWriter writer = new(filePath, true, Encoding.UTF8))
                    {
                        writer.WriteLine("关联ID,工单号,序列号,在库状态,入库日期,出库日期,跟踪结束日期,PCB丝印,状态,是否判断");
                        foreach (MaterialData2model item in list1)
                        {
                            conditionText = (item.Condition == 0) ? "在库" : (item.Condition == 1 ? "不在库" : "数据异常");
                            stateText = (item.State == 0) ? "正常" : (item.State == 1 ? "待核对" : (item.State == 2 ? "异常" : "数据异常"));
                            isJudgeText = (item.IsJudge == 0) ? "无" : (item.IsJudge == 1 ? "判断过" : "数据异常");

                            writer.WriteLine($"{item.Id2},{item.WorkOrderNumber},{item.SerialNumber},{conditionText}," +
                                $"{item.DeliveryDate},{item.OutboundDate},{item.EndDate},{item.ScreenPrinting},{stateText},{isJudgeText}");
                        }
                    }

                    this.response.SetSuccess($"导出成功！路径为：{filePath}");
                }
            }

            return this.response;
        }

        /// <summary>
        /// 物料追踪子表（新增）数据.
        /// </summary>
        /// <param name="id">主表与子表的关联id.</param>
        /// <returns>返回相关数据.</returns>
        [Route("/api/v1/material/MaterialRecord2Add")]
        [HttpPost]
        public async Task<ResponseModel> MaterialRecord2AddAsync(string id)
        {
            using (FactoryMesContext context = new())
            {
                var info1 = context.MaterialTracking2.FirstOrDefault(x => x.Id == id);
                var info2 = context.MaterialTracking3.FirstOrDefault(x => x.Id2 == id);

                // 设置请求头
                var client = new HttpClient(); // 创建了一个名为client的HttpClient实例，用于发送HTTP请求
                string[] array = info1.WorkOrder.Split(',');
                string str = JsonConvert.SerializeObject(array);
                var content = new StringContent(str, Encoding.UTF8, "application/json");
                string url = "http://10.9.1.110:8001/public/repairOrderQuery";

                // 发送 POST 请求
                HttpResponseMessage response = await client.PostAsync(url, content);

                // 处理响应结果
                var responseData = await response.Content.ReadAsStringAsync();
                RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(responseData);
                if (response.IsSuccessStatusCode)
                {
                    if (rootObject.data.Count >= 1)
                    {
                        // 更新
                        if (info2 != null)
                        {
                            foreach (var item in rootObject.data)
                            {
                                if (item.state == "不在库")
                                {
                                    var info4 = context.MaterialTracking3.Where(x => x.Id2 == id && x.SerialNumber == item.sn).FirstOrDefault();
                                    info4.OutboundDate = item.outStockTime[..10];
                                    info4.EndDate = DateTime.Parse(item.outStockTime[..10]).AddMonths(int.Parse(info1.EndDate)).ToString("yyyy-MM-dd");
                                    info4.Condition = 1; // 不在库
                                }
                            }

                            context.SaveChanges();
                            this.response.SetData(rootObject.data);
                        }

                        // 新增
                        else
                        {
                            foreach (var item in rootObject.data)
                            {
                                string screenPrinting = string.Empty;
                                var info3 = context.MainsortRecord.OrderByDescending(m => m.WarehousingDate).FirstOrDefault(x => x.One_Dimensional_Code == item.sn);
                                if (info3 != null && info3.Product_Category != "生产四部" && (info3.State == "6" || info3.State == "7" || info3.State == "8"))
                                {
                                    screenPrinting = context.RepairProduct.FirstOrDefault(x => x.ProductId == info3.ID).Data.Split("PCBsiyin")[1][11..].Split("\"}")[0];
                                }

                                MaterialData2Entity material = new()
                                {
                                    Id = RandomHelper.GetRandomizer(12, true, false, true, true), // 子id
                                    Id2 = id,        // 父id
                                    WorkOrderNumber = item.projectId,  // 工单号
                                    SerialNumber = item.sn,           // 序列号
                                    DeliveryDate = item.inStoreTime[..10],  // 入库日期
                                    OutboundDate = item.state == "不在库" ? item.outStockTime[..10] : null, // 出库日期
                                    EndDate = item.state == "不在库" ? DateTime.Parse(item.outStockTime[..10]).AddMonths(int.Parse(info1.EndDate)).ToString("yyyy-MM-dd") : null, // 跟踪结束日期
                                    Condition = item.state == "不在库" ? 1 : 0, // 不在库:在库
                                    ScreenPrinting = screenPrinting, // PCB丝印
                                    State = (info3 == null) ? 0 : ((DateTime.Parse(item.outStockTime[..10]).AddMonths(int.Parse(info1.EndDate)) - DateTime.Parse(info3.WarehousingDate[..10])).Days >= 0 ? 1 : 0), // 产品状态
                                    IsJudge = 0, // 是否判断过（0：无 1：判断过）
                                };
                                context.MaterialTracking3.Add(material);
                            }

                            context.SaveChanges();
                            this.response.SetData(rootObject.data);
                        }
                    }

                    // 工单无数据
                    else
                    {
                        this.response.SetError("未查询到该工单内相关数据");
                        return this.response;
                    }
                }
                else
                {
                    throw new HttpRequestException("接口响应异常！msg=" + response.StatusCode);
                }
            }

            return this.response;
        }

        /// <summary>
        /// 子表状态更改.
        /// </summary>
        /// <param name="id">唯一Id.</param>
        /// <param name="state">产品状态.</param>
        /// <returns>是否修改成功.</returns>
        [Route("/api/v1/material/materialRecord2Update")]
        [HttpPost]
        public ResponseModel MaterialRecord2Add(string id, int state)
        {
            using (FactoryMesContext context = new())
            {
                var info1 = context.MaterialTracking3.FirstOrDefault(x => x.Id == id);
                if (info1.Condition == 1 && (info1.State == 1 || info1.IsJudge == 1))
                {
                    if (info1 != null)
                    {
                        if (state == 0)
                        {
                            info1.State = 0;
                            info1.IsJudge = 1;
                        }
                        else if (state == 2)
                        {
                            info1.State = 2;
                            info1.IsJudge = 1;
                        }

                        context.SaveChanges();
                    }
                    else
                    {
                        this.response.SetData("无此记录");
                    }
                }
                else
                {
                    this.response.SetError("该产品不能进行状态更改");
                }
            }

            return this.response;
        }

        /// <summary>
        /// 子表数据删除.
        /// </summary>
        /// <param name="id">主表子表关联id.</param>
        /// <returns>返回修改状态.</returns>
        [Route("/api/v1/material/MaterialRecord2Delete")]
        [HttpGet]
        public ResponseModel MaterialRecord2Delete(string? id)
        {
            using (FactoryMesContext context = new())
            {
                var info1 = context.MaterialTracking3.FirstOrDefault(x => x.Id2 == id);
                var info2 = context.MaterialTracking2.FirstOrDefault(x => x.Id == id);
                if (!string.IsNullOrEmpty(id))
                {
                    if (info1 != null)
                    {
                        // 先删除，再查找
                        string sQL = string.Format("DELETE FROM MaterialTracking3 WHERE ID2 = '{0}';select a.ID2  from MaterialTracking3 a  where a.ID2 = '{0}'", id);
                        _ = context.Deletedata.FromSqlRaw(sQL).ToList();  // 执行SQL
                        info2.Abnormal = 0;
                    }
                    else
                    {
                        this.response.SetError("表格数据为空，无此数据");
                    }
                }
                else
                {
                    throw new ArgumentNullException(nameof(id));
                }

                context.SaveChanges();
            }

            return this.response;
        }
    }
}
